use std::sync::{atomic::AtomicBool, Arc};
use serde_json::json;
use webrtc::data_channel::RTCDataChannel;
use super::message_channel::IS_ACK;
use tokio::time::{sleep, Duration};
use crate::controller::channel::CONNECT_STATUS_CHANNEL;
use once_cell::sync::Lazy;
use std::sync::atomic::Ordering;

pub static CONTROL_CHANNEL_STATUS: Lazy<Arc<AtomicBool>> = Lazy::new(|| Arc::new(AtomicBool::new(false)));

// 在message通道获得握手应答后初始化
// 先发送授权请求
// 发送手柄连接状态(未连接)
// 延迟500ms (我也不知道为什么)
// 发送手柄连接状态(已连接)
// 接下来监听手柄连接状态
// 只有在连接状态变更的时候才需要发送变更状态
pub async fn control_channel_init(control_channel: Arc<RTCDataChannel>) {
    // 等待message通道握手完成
    loop {
        if IS_ACK.load(Ordering::SeqCst) {
            break;
        }
        // 防止异步阻塞
        sleep(Duration::from_millis(500)).await;
    }

    println!("message通道握手完成, 开始初始化control通道");
    let authorizationRequest = json!(
        {
            "message": "authorizationRequest",
            "accessKey": "4BDB3609-C1F1-4195-9B37-FEFF45DA8B8E"
        }
    ).to_string();

    control_channel.send_text(authorizationRequest).await.unwrap();
    control_channel.send_text(gamepad_disconnect()).await.unwrap();
    sleep(Duration::from_millis(500)).await;
    control_channel.send_text(gamepad_connect()).await.unwrap();

    let rx = CONNECT_STATUS_CHANNEL.1.clone();
    let channel_status = CONTROL_CHANNEL_STATUS.clone();
    // println!("control通道初始化完成, 开始监听手柄连接状态");
    tokio::spawn(
        async move{
            let mut rx = rx.lock().await;
            loop {
                tokio::select! {
                    // 防止死锁, 每隔1秒检查一次状态
                    biased;
                    Some(status) = rx.recv() => {
                        if(status == "controller connected") {
                            println!("线程通信: 收到手柄已连接");
                            control_channel.send_text(gamepad_connect()).await.unwrap();
                        } else if (status == "controller disconnected") {
                            println!("线程通信: 收到手柄已断开");
                            control_channel.send_text(gamepad_disconnect()).await.unwrap();
                        }
                    }
                    _ = sleep(Duration::from_secs(1)) => {
                        if !channel_status.load(Ordering::SeqCst) {
                            println!("control通道监听监听结束");
                            break;
                        }
                    }
                }
            }
        }
    );
    // 接下来将在异步任务自动处理手柄状态的变更事件

    println!("control通道初始化结束");
}

fn gamepad_connect() -> String{
    let json = json!(
        {
            "message": "gamepadChanged",
            "gamepadIndex": 0,
            "wasAdded": true
        }
    ).to_string();
    return json;
}
fn gamepad_disconnect() -> String {
    let json = json!(
        {
            "message": "gamepadChanged",
            "gamepadIndex": 0,
            "wasAdded": false
        }
    ).to_string();
    return json;
}